if (!window.PlayerListComponent) {
class PlayerListComponent {
  constructor(containerId = 'content') {
    this.container = document.getElementById(containerId);
    this.template = null;
    this.init();
  }

  async init() {
    await this.loadTemplate();
    this.renderSkeleton();
    this.renderData(); // 直接调用renderData metho
    this.bindEvents();
  }

  async loadTemplate() {
    const response = await fetch('/static/templates/playerlist-template.html');
    this.template = await response.text();
  }

  async renderData() {
    const datas = await this.fetchData();
    this.datas = datas;
    console.log(datas);
    
    const tbody = this.dataContainer.querySelector('.data-body');
    const thead = this.dataContainer.querySelector('.column-headers');
    
    // 动态生成表头
    const fieldOrder = ['idPlayerList', 'name', 'id', 'country', 'gender'];
    const fieldNames = {
      idPlayerList: 'Index',
      name: '姓名',
      id: 'ID',
      country: '国籍',
      gender: '性别'
    };
    
    const validFields = fieldOrder.filter(key => datas[0]?.hasOwnProperty(key));
    thead.innerHTML = validFields
      .map((key, index) => `<th data-col="${index}">${fieldNames[key]}</th>`)
      .join('');

    // 初始化分页状态
    this.currentPage = 1;
    this.pageSize = 20;
    this.totalPages = Math.ceil(datas.length / this.pageSize);

    // 渲染分页控件
    this.renderPagination();

    // 渲染当前页数据
    this.renderCurrentPageData(datas);
    
    // 默认选中第五列（索引1）
    this.setSelectedColumn(1);
  }

  renderCurrentPageData(datas) {
    // if (!Array.isArray(datas)) {
    //   console.warn('Invalid data source');
    //   return;
    // }
    console.log(datas);
    const tbody = this.dataContainer.querySelector('.data-body');
    const start = (this.currentPage - 1) * this.pageSize;
    const end = start + this.pageSize;
    const pageData = datas.slice(start, end);
    console.log(pageData);
    tbody.innerHTML = pageData.map(data => 
      `<tr>
        <td>${data.idPlayerList}</td>
        <td class="selected-column">${data.name}</td>
        <td>${data.id}</td>
        <td>${data.country}</td>
        <td>${data.gender === 1?"男":"女"}</td>
      </tr>`
    ).join('');
  }

  renderPagination() {
    const paginationContainer = this.dataContainer.querySelector('.pagination-container');
    if (!paginationContainer) {
      const container = document.createElement('div');
      container.className = 'pagination-container';
      container.innerHTML = `
        <button class="prev-page">上一页</button>
        <span>第 ${this.currentPage} 页 / 共 ${this.totalPages} 页</span>
        <button class="next-page">下一页</button>
      `;
      this.dataContainer.querySelector('.data-body').insertAdjacentElement('afterend', container);

      // 修复下一页按钮功能
      container.querySelector('.next-page').addEventListener('click', () => {
        if (this.currentPage < this.totalPages) {
          this.currentPage++;
          this.renderCurrentPageData(this.datas);
          this.updatePaginationDisplay();
        }
      });

      // 绑定分页事件
      container.querySelector('.prev-page').addEventListener('click', () => {
        if (this.currentPage > 1) {
          this.currentPage--;
          this.renderCurrentPageData(this.datas);
          this.updatePaginationDisplay();
        }
      });

      container.querySelector('.next-page').addEventListener('click', () => {
        if (this.currentPage < this.totalPages) {
          this.currentPage++;
          this.renderCurrentPageData(this.datas);
          this.updatePaginationDisplay();
        }
      });
    } else {
      this.updatePaginationDisplay();
    }
  }

  updatePaginationDisplay() {
    const paginationContainer = this.dataContainer.querySelector('.pagination-container');
    if (paginationContainer) {
      paginationContainer.querySelector('span').textContent = 
        `第 ${this.currentPage} 页 / 共 ${this.totalPages} 页`;
    }
  }

  renderSkeleton() {
    if (!this.container) {
      console.error('Container not initialized');
      return;
    }
    this.container.innerHTML = this.template;
    this.dataContainer = this.container.querySelector('.playerlist-container');
  }

  renderDataCSV(datas) {
    if (!Array.isArray(datas) || datas.length === 0) {
      console.warn('Invalid or empty data array');
      return;
    }
    this.datas2 = datas;
    const tbody = this.dataContainer.querySelector('.data2-body');
    const thead = this.dataContainer.querySelector('.column2-headers');
    
    // 渲染表头
    thead.innerHTML = ['Index', '姓名', 'id', '国籍', '性别']
      .map((text, index) => `<th data-col="${index}">${text}</th>`).join('');

    // 初始化分页状态
    this.currentPage2 = 1;
    this.pageSize2 = 20;
    this.totalPages2 = Math.ceil(datas.length / this.pageSize2);

    // 渲染分页控件
    this.renderPagination2();

    // 渲染当前页数据
    this.renderCurrentPageData2(datas);
  }

  renderCurrentPageData2(datas) {
    const tbody = this.dataContainer.querySelector('.data2-body');
    const start = (this.currentPage2 - 1) * this.pageSize2;
    const end = start + this.pageSize2;
    const pageData = datas.slice(start, end);

    tbody.innerHTML = pageData.map((row, index) => 
      `<tr>
        <td>${index + 1}</td>
        <td>${row[1]}</td>
        <td>${row[0]}</td>
        <td>${row[2]}</td>
        <td>${row[3]}</td>
      </tr>`
    ).join('');
  }

  renderPagination2() {
    const paginationContainer = this.dataContainer.querySelector('.pagination-container2');
    if (!paginationContainer) {
      const container = document.createElement('div');
      container.className = 'pagination-container2';
      container.innerHTML = `
        <button class="prev-page2">上一页</button>
        <span>第 ${this.currentPage2} 页 / 共 ${this.totalPages2} 页</span>
        <button class="next-page2">下一页</button>
      `;
      this.dataContainer.appendChild(container);

      // 绑定分页事件
      container.querySelector('.prev-page2').addEventListener('click', () => {
        if (this.currentPage2 > 1) {
          this.currentPage2--;
          this.renderCurrentPageData2(this.rawData);
          this.updatePaginationDisplay2();
        }
      });

      container.querySelector('.next-page2').addEventListener('click', () => {
        if (this.currentPage2 < this.totalPages2) {
          this.currentPage2++;
          this.renderCurrentPageData2(this.rawData);
          this.updatePaginationDisplay2();
        }
      });
    } else {
      this.updatePaginationDisplay2();
    }
  }

  updatePaginationDisplay2() {
    const paginationContainer = this.dataContainer.querySelector('.pagination-container2');
    if (paginationContainer) {
      paginationContainer.querySelector('span').textContent = 
        `第 ${this.currentPage2} 页 / 共 ${this.totalPages2} 页`;
    }
  }

  createConfigUI() {
    const configContainer = document.createElement('div');
    configContainer.className = 'config-container';

    // 添加表头行数选择
    configContainer.innerHTML += `
      <label>跳过表头行数:</label>
      <input type="number" class="header-rows" value="0">
    `;

    // 添加列映射选择
    const fields = ['id', 'name', 'country', 'gender'];
    fields.forEach(field => {
      configContainer.innerHTML += `
        <label>${field}列:</label>
        <select class="${field}-column">
          ${Array.from({length: 10}, (_, i) => `<option value="${i}">Column ${i + 1}</option>`).join('')}
        </select>
      `;
    });

    // 添加确认按钮
    configContainer.innerHTML += `
      <button class="apply-config">应用配置</button>
    `;

    this.container.appendChild(configContainer);

    // 绑定配置应用事件
    configContainer.querySelector('.apply-config').addEventListener('click', () => {
      const config = {
        headerRows: parseInt(configContainer.querySelector('.header-rows').value),
        columnMapping: {}
      };
      fields.forEach(field => {
        config.columnMapping[field] = parseInt(configContainer.querySelector(`.${field}-column`).value);
      });
      this.applyConfig(config);
    });
  }

  applyConfig(config) {
    if (!this.rawData || !Array.isArray(this.rawData)) {
      console.warn('No valid raw data available');
      return;
    }
    // 根据配置重新渲染数据
    const headerRows = config.headerRows;
    const columnMapping = config.columnMapping;

    const processedData = this.rawData.slice(headerRows).map(row => [
      row[columnMapping.id],
      row[columnMapping.name],
      row[columnMapping.country],
      row[columnMapping.gender]
    ]);
    console.log(processedData);
    this.renderDataCSV(processedData);
  }

  async handleFileUpload(e) {
    const file = e.target.files[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = async (event) =>{
      try {
        let data;
        if (file.name.endsWith('.csv')) {
          data = this.parseCSV(event.target.result);
        } else if (file.name.endsWith('.xlsx')) {
          data = await this.parseExcel(event.target.result);
        } else {
          throw new Error('不支持的文件格式');
        }
        this.rawData = data; // 保存原始数据
        this.createConfigUI(); // 显示配置界面
        // 初始显示原始数据
        const tbody = this.dataContainer.querySelector('.data-body');
        const thead = this.dataContainer.querySelector('.column-headers');
        thead.innerHTML = data[0].map((_, index) => `<th>Column ${index + 1}</th>`).join('');
        tbody.innerHTML = data.map(row => 
          `<tr>${row.map(cell => `<td>${cell}</td>`).join('')}</tr>`
        ).join('');
      } catch (error) {
        console.error('文件解析失败:', error);
        alert(`导入失败: ${error.message}`);
      }
    };
    // 使用 readAsArrayBuffer 替代 readAsBinaryString
    reader.readAsArrayBuffer(file);
  }

  async parseExcel(fileData) {
    const workbook = XLSX.read(await new Response(fileData).arrayBuffer(), {type: 'array'});
    const sheet = workbook.Sheets[workbook.SheetNames[0]];
    return XLSX.utils.sheet_to_json(sheet, {header: 1, defval: ''});
  }

  setSelectedColumn(colIndex) {
    document.querySelectorAll('.selected-column').forEach(el => el.classList.remove('selected-column'));
    document.querySelectorAll(`td:nth-child(${colIndex + 1}), th:nth-child(${colIndex + 1})`)
      .forEach(el => el.classList.add('selected-column'));
  }

  async fetchData() {
    const response = await fetch('/api/playerlist');
    return response.json();
  }

  bindEvents() {
    // 表格列点击事件
    this.dataContainer.querySelector('.column-headers').addEventListener('click', (e) => {
      if (e.target.tagName === 'TH') {
        const colIndex = parseInt(e.target.dataset.col);
        this.setSelectedColumn(colIndex);
      }
    });
    // 删除选手列表
    this.dataContainer.querySelector('.clearplayer-btn')?.addEventListener('click', async () => {
      const response = await fetch('/api/clearPlayers');
    });
    // 导入csv选手列表
    this.dataContainer.querySelector('.uploadcsv-btn')?.addEventListener('click', () => {
      const fileInput = document.createElement('input');
      fileInput.type = 'file';
      fileInput.accept = '.csv';
      fileInput.addEventListener('change', (e) => this.handleFileUpload(e));
      fileInput.click();
    });
    // 导入excel选手列表
    this.dataContainer.querySelector('.uploadexcel-btn')?.addEventListener('click', () => {
      const fileInput = document.createElement('input');
      fileInput.type = 'file';
      fileInput.accept = '.xlsx';
      fileInput.addEventListener('change', (e) => this.handleFileUpload(e));
      fileInput.click();
    });
    // 上传选手名单
    this.dataContainer.querySelector('.submit-btn')?.addEventListener('click', async () => {
      try {
        if (!this.datas2 || !this.datas2.length) {
          throw new Error('没有可上传的数据，请先导入文件并应用配置');
        }

        const params = this.datas2.map(row => ({
          playerid: row[0],
          name: row[1],
          country: row[2],
          gender: row[3] === '男'? 1 : row[3] === '女' ? 0 : 0 // 假设性别字段为第三列
        }));

        const response = await fetch('/api/upload-playerlist', {
          method: 'POST',
          headers: {'Content-Type': 'application/json'},
          body: JSON.stringify(params)
        });

        if (response.ok) {
          alert('选手名单上传成功！');
        } else {
          alert(`上传失败: ${await response.text()}`);
        }
      } catch (error) {
        console.error('上传错误:', error);
        alert(error.message || '网络请求失败');
      }
    })
  }

  async uploadCSVData(csvData) {
    // 保持原有上传逻辑
  }
}

window.PlayerListComponent = PlayerListComponent;
}
